import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userMenuAPI } from '../api/menu'
import type { MenuListType } from '@/types/menu'

// 定义菜单元数据接口
interface MenuMeta {
  title: string
  icon: string
  noCache: boolean
  link: string | null
}

// 定义菜单项接口
export interface MenuItem {
  name: string
  path: string
  hidden: boolean
  component: string
  redirect?: string
  alwaysShow?: boolean
  meta: MenuMeta
  children?: MenuItem[]
}

// 简化的菜单项，用于侧边栏显示
export interface SidebarItem {
  title: string
  path: string
  icon: string
  children?: SidebarItem[]
}

// 定义用户菜单项接口，用于头部下拉菜单
export interface HeaderMenuItem {
  name: string
  path: string
  icon: string
  title: string
}

// 本地存储键
const MENU_STORAGE_KEY = 'user_menu_data'
const SIDEBAR_STORAGE_KEY = 'sidebar_items'
const DYNAMIC_ROUTE_ADDED_KEY = 'dynamic_route_added'

// 检查本地存储的数据更新时间是否过期
// 默认24小时过期
const isStorageExpired = (storageKey: string, expirationHours: number = 24): boolean => {
  const timestamp = localStorage.getItem(`${storageKey}_timestamp`)
  if (!timestamp) return true
  
  const storedTime = parseInt(timestamp, 10)
  const currentTime = new Date().getTime()
  const expirationTime = expirationHours * 60 * 60 * 1000 // 转换为毫秒
  
  return (currentTime - storedTime) > expirationTime
}

// 定义菜单状态存储
export const useMenuStore = defineStore('menu', () => {
  // 状态
  const isCollapsed = ref(false)
  const menuList = ref<MenuListType[]>([])
  const sidebarItems = ref<SidebarItem[]>([])
  const isDynamicRouteAdded = ref(false)
  const headerMenuItems = ref([
    { name: 'profile', title: '个人资料', icon: 'user', path: '/profile/basic' },
    { name: 'password', title: '修改密码', icon: 'lock', path: '/profile/password' }
  ])
  
  // 计算属性：用于路由注册的菜单列表
  const dynamicMenuList = computed(() => {
    return menuList.value.filter(item => !item.hidden)
  })
  
  // 从localStorage初始化数据
  const initFromLocalStorage = () => {
    // 恢复侧边栏状态
    const storedCollapsed = localStorage.getItem('sidebar_collapsed')
    if (storedCollapsed) {
      isCollapsed.value = storedCollapsed === 'true'
    }
    
    // 恢复动态路由状态
    const storedDynamicRoute = localStorage.getItem(DYNAMIC_ROUTE_ADDED_KEY)
    if (storedDynamicRoute) {
      isDynamicRouteAdded.value = storedDynamicRoute === 'true'
    }
    
    // 恢复菜单数据
    const storedMenu = localStorage.getItem(MENU_STORAGE_KEY)
    const storedSidebar = localStorage.getItem(SIDEBAR_STORAGE_KEY)
    
    if (storedMenu && !isStorageExpired(MENU_STORAGE_KEY)) {
      try {
        menuList.value = JSON.parse(storedMenu)
        console.log('从本地存储加载菜单数据')
      } catch (e) {
        console.error('解析本地菜单数据失败:', e)
      }
    }
    
    if (storedSidebar && !isStorageExpired(SIDEBAR_STORAGE_KEY)) {
      try {
        sidebarItems.value = JSON.parse(storedSidebar)
        console.log('从本地存储加载侧边栏数据')
      } catch (e) {
        console.error('解析本地侧边栏数据失败:', e)
      }
    }
  }
  
  // 保存数据到localStorage
  const saveToLocalStorage = () => {
    localStorage.setItem(MENU_STORAGE_KEY, JSON.stringify(menuList.value))
    localStorage.setItem(SIDEBAR_STORAGE_KEY, JSON.stringify(sidebarItems.value))
    localStorage.setItem(`${MENU_STORAGE_KEY}_timestamp`, String(new Date().getTime()))
    localStorage.setItem(`${SIDEBAR_STORAGE_KEY}_timestamp`, String(new Date().getTime()))
    localStorage.setItem('sidebar_collapsed', String(isCollapsed.value))

    console.log(localStorage.setItem(MENU_STORAGE_KEY, JSON.stringify(menuList.value)));
    console.log(localStorage.setItem(SIDEBAR_STORAGE_KEY, JSON.stringify(sidebarItems.value)));
    console.log(localStorage.setItem(`${MENU_STORAGE_KEY}_timestamp`, String(new Date().getTime())));
    console.log(localStorage.setItem(`${SIDEBAR_STORAGE_KEY}_timestamp`, String(new Date().getTime())));
    console.log(localStorage.setItem('sidebar_collapsed', String(isCollapsed.value)));
  }
  
  // 方法：切换侧边栏收起/展开状态
  const toggleSidebar = () => {
    isCollapsed.value = !isCollapsed.value
    localStorage.setItem('sidebar_collapsed', String(isCollapsed.value))
  }
  
  // 方法：设置动态路由添加状态
  const setDynamicRouteAdded = (status: boolean) => {
    isDynamicRouteAdded.value = status
    localStorage.setItem(DYNAMIC_ROUTE_ADDED_KEY, String(status))
  }
  
  // 方法：处理头部菜单选择
  const handleHeaderMenuSelect = (name: string) => {
    // 找到对应的菜单项
    const menuItem = headerMenuItems.value.find(item => item.name === name);
    if (menuItem) {
      return menuItem.path;
    }
    return null;
  }
  
  // 方法：获取用户菜单
  const fetchUserMenu = async (forceRefresh = false) => {
    // 如果有本地缓存且未过期，且不强制刷新，则直接返回本地数据
    if (!forceRefresh && 
        menuList.value.length > 0 && 
        sidebarItems.value.length > 0 && 
        !isStorageExpired(MENU_STORAGE_KEY)) {
      console.log('使用本地缓存的菜单数据')
      return {
        success: true,
        message: '从本地存储加载菜单成功',
        data: menuList.value
      }
    }
    
    try {
      const result = await userMenuAPI()
      
      if (result.success && result.data) {
        menuList.value = result.data
        
        // 转换为侧边栏菜单
        sidebarItems.value = convertToSidebarItems(result.data)
        
        // 保存到本地存储
        saveToLocalStorage()
        
        // 调试输出菜单数据
        console.log('获取到菜单数据:', menuList.value)
        
        return {
          success: true,
          message: result.message,
          data: menuList.value
        }
      } else {
        console.error('获取菜单失败:', result.message)
        
        // 如果API请求失败但本地有数据，仍使用本地数据
        if (menuList.value.length > 0) {
          return {
            success: true,
            message: '使用本地缓存数据',
            data: menuList.value
          }
        }
        
        return {
          success: false,
          message: result.message,
          data: null
        }
      }
    } catch (error) {
      console.error('获取菜单请求出错:', error)
      
      // 如果API请求出错但本地有数据，仍使用本地数据
      if (menuList.value.length > 0) {
        return {
          success: true,
          message: '使用本地缓存数据',
          data: menuList.value
        }
      }
      
      return {
        success: false,
        message: '获取菜单请求出错',
        data: null
      }
    }
  }
  
  // 方法：转换为侧边栏菜单项
  const convertToSidebarItems = (menuItems: MenuListType[]): SidebarItem[] => {
    return menuItems.map(item => {
      // 创建侧边栏菜单项
      const sidebarItem: SidebarItem = {
        title: item.meta.title,
        path: item.path,
        icon: item.meta.icon
      }
      
      // 如果有子菜单，递归转换
      if (item.children && item.children.length > 0) {
        // 为子菜单项生成完整路径
        const childItems = item.children.map(child => {
          // 如果子菜单路径不是绝对路径（不以/开头），则拼接父路径
          if (!child.path.startsWith('/')) {
            // 确保父路径和子路径之间只有一个斜杠
            const parentPath = item.path.endsWith('/') ? item.path.slice(0, -1) : item.path;
            return {
              ...child,
              path: `${parentPath}/${child.path}`
            };
          }
          return child;
        });
        
        sidebarItem.children = convertToSidebarItems(childItems);
      }
      
      return sidebarItem
    })
  }
  
  // 方法：重置菜单数据
  const resetMenuState = () => {
    console.log('重置菜单状态和清除菜单缓存')
    
    // 重置内存中的状态
    menuList.value = []
    sidebarItems.value = []
    isDynamicRouteAdded.value = false
    
    // 清除本地存储的所有菜单和路由相关数据
    clearMenuStorage()
  }
  
  // 静态方法：清除菜单存储数据，可以被其他store调用
  const clearMenuStorage = () => {
    // 清除菜单数据
    localStorage.removeItem(MENU_STORAGE_KEY)
    localStorage.removeItem(SIDEBAR_STORAGE_KEY)
    localStorage.removeItem(`${MENU_STORAGE_KEY}_timestamp`)
    localStorage.removeItem(`${SIDEBAR_STORAGE_KEY}_timestamp`)
    
    // 清除路由状态
    localStorage.removeItem(DYNAMIC_ROUTE_ADDED_KEY)
    
    // 如果需要保留侧边栏折叠状态，则注释掉下面这行
    localStorage.removeItem('sidebar_collapsed')
  }
  
  // 初始化时从本地存储加载数据
  initFromLocalStorage()
  
  return {
    isCollapsed,
    menuList,
    sidebarItems,
    headerMenuItems,
    isDynamicRouteAdded,
    dynamicMenuList,
    toggleSidebar,
    handleHeaderMenuSelect,
    getUserMenu: fetchUserMenu,
    resetMenuState,
    setDynamicRouteAdded,
    clearMenuStorage // 暴露清除菜单存储方法
  }
})